//
// Copyright (c) 2023 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef SERVERTECHCHAT_SERVER_INCLUDE_SERVICES_SESSION_STORE_HPP
#define SERVERTECHCHAT_SERVER_INCLUDE_SERVICES_SESSION_STORE_HPP

#include <boost/asio/spawn.hpp>

#include <chrono>
#include <string_view>

#include "error.hpp"

// Contains functions to manage user sessions. This are stored in Redis as
// (session_id, user_id) pairs, with a certain expiry time. Sessions last
// until their corresponding Redis key expires or is removed.
// These functions are relatively low-level. Prefer cookie_auth_service.hpp
// to check auth in API handlers.

namespace chat {

// Forward declaration
class redis_client;

class session_store
{
    redis_client* redis_;

public:
    session_store(redis_client& cli) noexcept : redis_(&cli) {}

    // Generates and stores a new session for the given user, with a certain duration
    result_with_message<std::string> generate_session_id(
        std::int64_t user_id,
        std::chrono::seconds session_duration,
        boost::asio::yield_context yield
    );

    // Retrieves the user ID associated to the passed session ID. Session IDs
    // are generated by generate_session_id.
    // Returns errc::not_found if the given session ID doesn't exist.
    result_with_message<std::int64_t> get_user_by_session(
        std::string_view session_id,
        boost::asio::yield_context yield
    );
};

}  // namespace chat

#endif
